use image::{DynamicImage, ImageError, ImageFormat};
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Write};
use wasm_bindgen::prelude::*;

pub fn convert_to_webp(image: &[u8]) -> Result<Vec<u8>, JsValue> {
    let img: DynamicImage = image::load_from_memory(image)
        .map_err(|e: ImageError| JsValue::from_str(&format!("unsupported image type: {:?}", e)))?;

    let encoded: Vec<u8> = Vec::new();
    let mut cursor = Cursor::new(encoded);
    img.write_to(&mut cursor, ImageFormat::WebP).unwrap();
    let encoded = cursor.into_inner();

    // 返回 WebP 数据
    Ok(encoded)
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 打开并读取输入的二进制文件
    let img_path = "panit3.jpg"; // 或者 "input.jpg"
    let img_file = File::open(img_path)?;
    let mut reader = BufReader::new(img_file);
    let mut buffer = Vec::new();
    reader.read_to_end(&mut buffer)?;

    // 调用转换函数
    match convert_to_webp(&buffer) {
        Ok(webp_data) => {
            // 将 WebP 数据写入文件
            let mut webp_file = File::create("output.webp")?;
            webp_file.write_all(&webp_data)?;
            println!("Conversion successful! WebP image saved as 'output.webp'.");
        }
        Err(e) => {
            println!("Conversion failed: {:?}", e);
        }
    }

    Ok(())
}
